package com.danskin.wechat.web;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.github.pagehelper.util.StringUtil;
import com.danskin.wechat.entity.CustItemRecord;
import com.danskin.wechat.service.CustItemRecordService;
import com.danskin.wechat.util.Page;
@Controller
@RequestMapping("custItemRecord")
public class CustItemRecordController extends BaseController{
	@Resource
    private CustItemRecordService custItemRecordService;
	
	
	/***
	 * 查询订单
	 * @param custItemRecord
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "queryCustItemRecordList", method = RequestMethod.GET)
	public String queryCarouselInfoList(CustItemRecord custItemRecord,Model model){
		return "custItemRecord/custItemRecord_list";
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getCustItemRecordList", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Object getCarouselInfoList(Page page,HttpServletRequest request) throws Exception {
		Map map = getRequestParameter(this.getRequest());
		map.put("mpId", this.getMpId());
		page.setMap(map);
		List<CustItemRecord> listCustItemRecord = custItemRecordService.getCustItemRecordList(page);
		return pagelistToJSONForBootStrapTable(getConversionCustItemRecord(listCustItemRecord), page);
	}
	/***
	 * 修改订单信息
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "updateCustItemRecord",method = RequestMethod.GET)
	public String  updateCustItemRecord(HttpServletRequest request,Model model){
		String id = request.getParameter("id");
		CustItemRecord custItemRecord = null;
		if(StringUtil.isNotEmpty(id)){
			custItemRecord = custItemRecordService.findCustItemRecordById(id);
		}
		model.addAttribute("custItemRecord", custItemRecord);
		return "custItemRecord/updateCustItemRecord";
	}
	/***
	 * 保存修改订单
	 * @param request
	 * @param custItemRecord
	 * @param productInfo
	 * @return
	 */
	@RequestMapping(value = "saveCustItemRecord",method = RequestMethod.POST)
	public String saveCustItemRecord(HttpServletRequest request,CustItemRecord custItemRecord, CustItemRecord productInfo){
		try {
			int cout = custItemRecordService.updateCustItemRecord(custItemRecord);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/custItemRecord/queryCustItemRecordList"; 
	}
	/***
	 * 导出订单管理数据
	 * @param request
	 * @param response
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "exportCustItemRecord", method = RequestMethod.GET)
	public void exportCustItemRecord(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException{
		SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String orderNo = request.getParameter("orderNo");
		String parameter = request.getParameter("parameter");
		String startTime = request.getParameter("startTime");
		String endTime = request.getParameter("endTime");
		String mpId = String.valueOf(this.getMpId());
		String mobile = null;
		String name = null;
		if(StringUtil.isNotEmpty(parameter)){
			if(isNumeric(parameter)){
				mobile = parameter;
			}else{
				name = parameter;
			}
		}
		List<CustItemRecord> custItemRecordList = custItemRecordService.getCustItemRecordExport(orderNo,mobile,name,startTime,endTime,mpId);
		HSSFWorkbook wb = new HSSFWorkbook();  
		HSSFSheet sheet = wb.createSheet("订单管理统计");
		HSSFRow row = sheet.createRow((int) 0);    
		HSSFCellStyle style = wb.createCellStyle();    
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式 
        HSSFCell cell = row.createCell((short) 0);    
        cell.setCellValue("订单号");    
        cell.setCellStyle(style);    
        cell = row.createCell((short) 1);    
        cell.setCellValue("收件人");    
        cell.setCellStyle(style);    
        cell = row.createCell((short) 2);    
        cell.setCellValue("收件电话");    
        cell.setCellStyle(style);    
        cell = row.createCell((short) 3); 
        cell.setCellValue("收件地址");    
        cell.setCellStyle(style); 
        cell = row.createCell((short) 4); 
        cell.setCellValue("商品名称");    
        cell.setCellStyle(style); 
        cell = row.createCell((short) 5); 
        cell.setCellValue("模板ID");    
        cell.setCellStyle(style); 
        cell = row.createCell((short) 6); 
        cell.setCellValue("会员手机号");    
        cell.setCellStyle(style); 
        cell = row.createCell((short) 7);  
        cell.setCellValue("运费");    
        cell.setCellStyle(style);       
        cell = row.createCell((short) 8);    
        cell.setCellValue("总价");    
        cell.setCellStyle(style);
        cell = row.createCell((short) 9);    
        cell.setCellValue("状态");    
        cell.setCellStyle(style);
        cell = row.createCell((short) 10);    
        cell.setCellValue("下单时间");    
        cell.setCellStyle(style);
        for (int i = 0; i < custItemRecordList.size(); i++)  {
        	row = sheet.createRow((int) i + 1);  
        	CustItemRecord am = custItemRecordList.get(i);
        	String area = am.getProvince()==null?"":am.getProvince();
			String city = am.getCity()==null?"":am.getCity();
			String county = am.getDistrict()==null?"":am.getDistrict();
			String address = am.getDetailAddress()==null?"":am.getDetailAddress();
        	row.createCell((short) 0).setCellValue(am.getOrderNo());  
        	if(StringUtil.isNotEmpty(am.getConsigneeName())){
        		row.createCell((short) 1).setCellValue(am.getConsigneeName());
        	}
            if(StringUtil.isNotEmpty(am.getConsigneeMobile())){
            	row.createCell((short) 2).setCellValue(am.getConsigneeMobile()); 
        	}
            row.createCell((short) 3).setCellValue(area+city+county+address);            
            row.createCell((short) 4).setCellValue(am.getProductName());
            row.createCell((short) 5).setCellValue(am.getCouponTemplateId());
            row.createCell((short) 6).setCellValue(am.getMobile());     
            row.createCell((short) 7).setCellValue(String.valueOf(am.getTotalAmount())); 
            row.createCell((short) 8).setCellValue(am.getTotalPoints()); 
            if(am.getOrderStatus()==0){
            	 row.createCell((short) 9).setCellValue("待审核"); 
            }else if(am.getOrderStatus()==1){
            	 row.createCell((short) 9).setCellValue("已审核确认"); 
            }else if(am.getOrderStatus()==2){
            	 row.createCell((short) 9).setCellValue("审核未通过"); 
            }else if(am.getOrderStatus()==3){
            	 row.createCell((short) 9).setCellValue("客户已确认(待发货)"); 
            }else if(am.getOrderStatus()==4){
            	 row.createCell((short) 9).setCellValue("已发货"); 
            }else if(am.getOrderStatus()==5){
            	 row.createCell((short) 9).setCellValue("已完成"); 
            }else{
            	 row.createCell((short) 9).setCellValue("订单作废"); 
            }
            if(am.getCreatedTime()!=null){
            	cell = row.createCell((short) 10); 
            	cell.setCellValue(dateFormater.format(am.getCreatedTime()));
            }
        }
        OutputStream out = null;   
        try {        
            out = response.getOutputStream();    
            String fileName = "订单管理统计.xls";// 文件名        
            response.setContentType("application/x-download");
            response.setCharacterEncoding("utf-8"); 
            response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("gbk"), "iso8859-1"));
            wb.write(out);   
        } catch (Exception e) {    
            e.printStackTrace();    
        } finally {      
            try {       
                out.close();      
            } catch (IOException e) {      
                e.printStackTrace();    
            }      
        }  
        	
	}
	private  boolean isNumeric(String str){
	    Pattern pattern = Pattern.compile("[0-9]*");
	    return pattern.matcher(str).matches();   
	}
	private List<CustItemRecord> getConversionCustItemRecord(List<CustItemRecord> listCustItemRecord){
		List<CustItemRecord> list = new ArrayList<CustItemRecord>();
		if(listCustItemRecord.size()>0){
			for(CustItemRecord record:listCustItemRecord){
				CustItemRecord cr = new CustItemRecord();
				cr.setId(record.getId());
				cr.setMpId(record.getMpId());
				cr.setCustExId(record.getCustExId());
				cr.setOrderNo(record.getOrderNo());
				cr.setTotalPoints(record.getTotalPoints());
				cr.setTotalAmount(record.getTotalAmount());
				cr.setConsigneeName(record.getConsigneeName());
				cr.setConsigneeMobile(record.getConsigneeMobile());
				cr.setConsigneeTel(record.getConsigneeTel());
				cr.setTown(record.getTown());
				cr.setOrderStatus(record.getOrderStatus());
				cr.setFinishedTime(record.getFinishedTime());
				cr.setShipperCode(record.getShipperCode());
				cr.setShippingNo(record.getShippingNo());
				cr.setCreatedTime(record.getCreatedTime());
				cr.setLastModifiedTime(record.getLastModifiedTime());
				cr.setProductId(record.getProductId());
				String area = record.getProvince()==null?"":record.getProvince();
				String city = record.getCity()==null?"":record.getCity();
				String county = record.getDistrict()==null?"":record.getDistrict();
				String address = record.getDetailAddress()==null?"":record.getDetailAddress();
				cr.setAddress(area+city+county+address);
				cr.setMobile(record.getMobile());
				cr.setProductName(record.getProductName());
				cr.setCouponTemplateId(record.getCouponTemplateId());
				list.add(cr);
			}
		}
		return list;
	} 
}
